package com.consult.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.consult.config.dto.LoginDto;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class TokenUtil {

    private static final long EXPIRE_TIME = 10 * 60 * 60 * 1000;//token到期时间10小时
    private static final String TOKEN_SECRET = "ljdyaishijin**3nkjnj??";  //密钥盐

    /**
     * @param : [user]
     * @param userType
     * @return : java.lang.String
     * @Description ：生成token
     */
    public static String sign(LoginDto user, Integer userType) {
        String token = null;
        try {
            Date expireAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            token = JWT.create()
                    .withIssuer("auth0")//发行人
                    .withClaim("username", user.getName())//存放数据
                    .withClaim("userId", user.getId())//存放数据
                    .withClaim("userType", userType)
                    .withExpiresAt(expireAt)//过期时间
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (IllegalArgumentException | JWTCreationException je) {

        }
        return token;
    }


    /**
     * @param : [token]
     * @return : java.lang.Boolean
     * @Description ：token验证
     */
    public static Boolean verify(String token) {
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();//创建token验证器
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            System.out.println("认证通过：");
            System.out.println("username: " + decodedJWT.getClaim("username").asString());
            System.out.println("过期时间：      " + decodedJWT.getExpiresAt());
        } catch (IllegalArgumentException | JWTVerificationException e) {
            //抛出错误即为验证不通过
            return false;
        }
        return true;
    }

    /**
     * 获取用户名
     *
     * @param token
     * @return
     */
    public static String getUserName(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获取用户名
     *
     * @param request
     * @return
     */
    public static Long getUserId(HttpServletRequest request) {
        String token = request.getHeader("x-token");// 从 http 请求头中取出 token
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asLong();
        } catch (JWTDecodeException e) {
            return null;
        }
    }


}
